
$(document).ready(function () {

    $.validator.setDefaults({
        errorClass: "uk-text-danger",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass("uk-form-danger");
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass("uk-form-danger");
        }
    });

    AccountInfoDialog.setupFormValidation();
    AccountSearchBox.setupFormValidation();

    AccountInfoDialog.addSaveButtonClickHandler(onAccountSave);

    $('#btn_search').click(onSearch);
    $('#btn_reset').click(AccountSearchBox.resetForm);
});

var blockingModal;
function onSearch() {
    AccountSearchBox.doSearch(
        function() {
            blockingModal = UIkit.modal.blockUI("正在搜索...");
        },
        function (data) {
            try {
                if (data != null && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var account = data[i];
                        accountList.add(account);
                    }
                } else {
                    UIkit.notify("未找到用户");
                }
            } catch (e) {
                console.error(e);
            }
        },
        function (jqXHR) {
            try {
                var response = JSON.parse(jqXHR.responseText);
                if (response != null && response.error != null) {
                    UIkit.modal.alert("发生错误: " + response.error.message);
                } else {
                    UIkit.modal.alert("发生错误。");
                }
            } catch (e) {
                console.error(e);
                UIkit.modal.alert("发生错误。")
            }
        },
        function () {
            blockingModal.hide();
        }, true);
}

function accountToTableRow(account, index) {
    var username = null;
    var userType = null;
    var name = null;
    if (account.student != null) {
        username = account.student.studentNumber;
        userType = "学生";
        name = account.student.name;
    } else {
        username = account.teacher.teacherNumber;
        userType = "教师";
        name = account.teacher.name;
    }

    var a = $("<a>查看</a>");
    a.click(openAccountInfoDialog);
    var detailTableCell = $("<td></td>").append(a);

    var tableRow = $("<tr></tr>")
        .append($("<td class=\"index-table-cell\">" + index + "</td>"))
        .append("<td>" + username + "</td>")
        .append("<td>" + userType + "</td>")
        .append("<td>" + name + "</td>")
        .append(detailTableCell);

    return tableRow
}

function openAccountInfoDialog() {
    AccountInfoDialog.resetAccountInfoDialog();

    var index = parseInt($(this).parent().prevAll()[3].textContent) - 1;
    var account = accountList.accounts[index];
    if (account == null) {
        UIkit.notify("无法查看该账号。", {status: 'danger'});
        return;
    } else {
        $('#account_index')[0].value = index;
        AccountInfoDialog.fillUpForms(account);
    }

    AccountInfoDialog.showDialog();
}

function onAccountSave() {
    // console.log("account saved");
    // AccountInfoDialog.hideDialog();
    var index = $('#account_index')[0].value;
    var oldAccount = accountList.accounts[index];

    var userType = $('#account_user_type')[0].value;
    if (userType !== oldAccount.userType) {
        UIkit.modal.alert('非法修改不可更改项');
        return;
    }

    var newAccount = { userType: userType };
    var form;
    if (userType === 'S') {
        form = $('#form_student_info');

        if (form.valid()) {
            var student = form.serializeJSON({ skipFalsyValuesForTypes: ['number', 'string'] });
            student.studentNumber = oldAccount.student.studentNumber;
            newAccount.student = student;
        } else {
            return;
        }

    } else if (userType === 'T') {
        form = $('#form_teacher_info');

        if (form.valid()) {
            var teacher = form.serializeJSON({ skipFalsyValuesForTypes: ['number', 'string'] });
            teacher.teacherNumber = oldAccount.teacher.teacherNumber;
            newAccount.teacher = teacher;
        }

    }

    blockingModal = UIkit.modal.blockUI('正在提交修改...');
    $.ajax({
        url: '/api/admin/update_account',
        data: JSON.stringify(newAccount),
        contentType: 'application/json',
        type: 'PUT'
    })
        .done(function () {
            newAccount.name = oldAccount.name;
            accountList.replace(newAccount, index);
            AccountInfoDialog.hideDialog();
            UIkit.notify('修改成功！', { status: 'success'});
        })
        .fail(function (jqXHR) {
            try {
                var response = JSON.parse(jqXHR.responseText);
                if (response != null && response.error != null) {
                    UIkit.modal.alert("发生错误: " + response.error.message);
                } else {
                    UIkit.modal.alert("发生错误。");
                }
            } catch (e) {
                console.error(e);
                UIkit.modal.alert("发生错误。");
            }
        })
        .always(function () {
            blockingModal.hide();
        });


}